package logic

import (
	"context"
	"encoding/json"
	"errors"
	"short-video-dev/cache"
	"short-video-dev/mysql"
	"time"

	"short-video-dev/videorpc/internal/svc"
	"short-video-dev/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type VideoDetailLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewVideoDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *VideoDetailLogic {
	return &VideoDetailLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 视频详情
func (l *VideoDetailLogic) VideoDetail(in *videorpc.VideoDetailRequest) (*videorpc.VideoDetailResponse, error) {
	// todo: add your logic here and delete this line

	var detail *videorpc.VideoDetailResponse
	result, _ := cache.Rdb.Get(l.ctx, "video").Result()
	if result == "" {
		detail, err := mysql.VideoDetail(mysql.DB, in.VideoId)
		if err != nil {
			return nil, errors.New("视频不存在")
		}
		marshal, _ := json.Marshal(detail)
		cache.Rdb.Set(l.ctx, "video", marshal, time.Minute*10)
	} else {
		json.Unmarshal([]byte(result), &detail)
	}

	var list []*videorpc.VideoList
	list = mysql.VideoPush(mysql.DB)

	return &videorpc.VideoDetailResponse{
		VideoTitle:    detail.VideoTitle,
		VideoCategory: detail.VideoCategory,
		VideoLink:     detail.VideoLink,
		VideoIntro:    detail.VideoIntro,
		PlayNum:       detail.PlayNum,
		LikeNum:       detail.LikeNum,
		CollectNum:    detail.CollectNum,
		CommentNum:    detail.CommentNum,
		NikeName:      detail.NikeName,
		HeadImage:     detail.HeadImage,
		List:          list,
	}, nil
}
